package day09.test1;

import java.util.Random;
import java.util.Scanner;

class GenRandom extends Thread {
    //生成随机数的数量 -- 顺序型生成数量，和线程的生成数量不同
    private final int max;

    GenRandom(int m) {
        max = m;
    }

    //生成max个随机数--不要输出、不要保存，无意义，且浪费时间
    private static void genRandom(int max) {
        Random r = new Random();
        for (int i = 0; i < max; i++)
            r.nextInt();
    }

    //顺序型生成--max=100万
    public static void seqGen(int max) {
        genRandom(max);
    }

    //用线程生成--4个线程，max=25万
    @Override
    public void run() {
        genRandom(max);
    }
}

public class GenNumber {
    public static void main(String[] args) throws InterruptedException {
        //这里取1000万，太小很难计算时间
        final int max = 100000000;
        //获取开始时间
        long startTime = System.currentTimeMillis();
        //执行顺序型
        GenRandom.seqGen(max);
        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("顺序型运行时间：" + (endTime - startTime) + "ms");


        //创建4个线程

        Scanner res = new Scanner(System.in);
        System.out.println("请问要多少个线程");
        int num = res.nextInt();
        int arr = max / num;
        int right_num = max - arr * (num - 1);

        startTime = System.currentTimeMillis();
        GenRandom[] threads = new GenRandom[num];
        for (int i = 0; i < num; i++) {
            if (i == (num - 1)) {
                threads[i] = new GenRandom(right_num);
                threads[i].start();
                continue;
            }
            threads[i] = new GenRandom(arr);
            threads[i].start();
        }
        //等待所有线程执行完毕
        for (int i = 0; i < 4; i++) {
            threads[i].join();
        }

        endTime = System.currentTimeMillis();
        System.out.println("多线程运行时间：" + (endTime - startTime) + "ms");

    }
}